package com.goktech.interceptor;

import com.goktech.utils.UserHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor");
        // 判断 ThreadLocal 中是否有用户
        if (ObjectUtils.isEmpty(UserHolder.getUser())) {
            // 不存在, 拦截, 返回 401
            System.out.println("ThreadLocal 中没有用户");
            response.setStatus(401);
            return false;
        }
        System.out.println("ThreadLocal 中有用户");
        // 有用户, 放行
        return true;
    }
}
